<template>
	<view>
		<!-- <u-navbar :is-back="false" :is-fixed="true" title="市场"></u-navbar> -->
		<view class="fixed-top bg-white">
			<view class="px-3 tab-item" v-for="(item,index) in tabBars" :id="'tab'+index" @click="changeTab(index)"
				:key="index">
				<view class="font-md" :class="tabIndex === index ? 'text-8ED0F2 font-weight-bold font-lg':''">
					{{item.name}}
				</view>
			</view>
			<view class="px-2 mt-2 pb-2">
				<u-search placeholder="请输入关键字 " height="60" border-color="#8ED0F2" search-icon-color="#8ED0F2"
					bg-color="#fff" v-model="keyword" @input="search" :action-style="actionStyle"></u-search>
			</view>
			<u-gap height="20" bg-color="#f7f7f7"></u-gap>
		</view>
		<scroll-view scroll-y scroll-with-animation style="height: calc(100vh - 50px);" class="mt-13 pb-6"
			:show-scrollbar="false" @scrolltolower="loadMore" @scrolltoupper="refresh">
			<view class=" p-2" style="margin-top: 25px;">
				<view v-for="(item, index) in tabData" :key="index" class="pb-2  mt-2 content-item u-line">
					<view class="font-14 text-333333 font-weight-bold">
						{{tabIndex === 0 ? item.productServeName : item.title}}
					</view>
					<view class="dfex mt-2">
						<view class="text-A0A0A0 font-14 lineHight" @click="openDetails(item.id, tabIndex)">
							<view>
								{{tabIndex === 0 ? '上游服务商' : '产品名称'}}：{{tabIndex === 0 ? item.serviceName : item.productName}}
							</view>
							<view class="wraps">
								{{tabIndex === 0 ? '服务介绍' : '需求价格'}}：{{tabIndex === 0 ? item.serviceIntroduction : item.price + '元'}}
							</view>
							<view>
								{{tabIndex === 0 ? '服务价格' : '截止日期'}}：{{tabIndex === 0 ? item.servicePrice + '元' : item.endTime}}
							</view>
						</view>
						<view class="lineHight-3">
							<view>
								<u-button size="mini" type="warning" shape="circle"
									@click="makePhoneCall(tabIndex)">电话咨询</u-button>
							</view>
							<view>
								<u-button size="mini" type="success" shape="circle"
									@click="addService(tabIndex, item.id, item.id)">使用服务</u-button>
							</view>


						</view>
					</view>
				</view>
				<view v-if="!hasMore && tabData.length > 0" class="text-center mt-3 mb-3">
					<view class="text-muted">没有更多数据了</view>
				</view>
				<view v-else-if="!hasMore && tabData.length === 0" class="text-center mt-3 mb-3">
					<view class="iconfont text-999999 icon-zanwushuju font-48 pb-1"></view>
					<view class="text-999999 font-15">暂无数据</view>
				</view>
				<view v-else class="text-center mt-3 mb-3">
					<view class="btn btn-primary">加载更多</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import $H from '@/common/free-lib/request.js';

	export default {
		data() {
			return {
				tabBars: [{
						"id": 1,
						"name": "上游市场",
					},
					{
						"id": 2,
						"name": "下游市场",
					},
				],
				tabIndex: 0,
				keyword: '',
				tabData: [],
				phone: '',
				form: {
					pageNo: 1,
					pageSize: 10,
					total: 0 // 总页数
				},
				hasMore: true,
				id: '',
				upperMarketProductId: '',
				downMarketDemandId: '',
				actionStyle: {
					color: '#8ED0F2'
				},
			};
		},
		onShow() {
			this.fetchData();
			this.tabData = []
		},
		methods: {
			setDefaultPageConfig() {
				this.form.pageNo = 1
				this.form.pageSize = 10
				this.form.total = 0
			},
			search() {
				if (this.keyword.trim() === '') {
					// 如果关键字为空，则显示原始数据
					this.isSearching = false;
					this.hasMore = true;
					this.tabData = []; // 清空列表数据
					this.setDefaultPageConfig();
					this.fetchData();
					return;
				}
				this.tabData = []
				this.setDefaultPageConfig()
				this.fetchData()
			},
			// 获取数据
			fetchData() {
				uni.showLoading({
					title: '加载中'
				});
				const api = this.tabIndex === 0 ?
					'/upper/upperMarketProduct/agriculture/list' :
					'/down/downMarketDemand/agriculture/list';
				const requestData = this.tabIndex === 0 ? {
					productServeName: this.keyword.trim()
				} : {
					title: this.keyword.trim()
				};

				$H.get(api, {
					...this.form,
					...requestData
				}).then(res => {
					this.tabData = [...this.tabData, ...res.result.records];
					this.phone = res.result.records[0]?.phone;
					this.form.total = res.result.total;
					this.page++;
					this.hasMore = this.tabData.length < this.form.total;
					uni.hideLoading();
				}).catch(error => {
					console.error('网络错误，请稍后再试', error);
					uni.hideLoading();
				});
			},

			// 拨打电话
			makePhoneCall(tabIndex) {
				this.showModal('拨打电话', '确定要拨打电话吗？', () => this.doMakePhoneCall(tabIndex));
			},
			// 执行拨打电话
			doMakePhoneCall(tabIndex) {
				const phone = this.tabData[0]?.phone;
				uni.makePhoneCall({
					phoneNumber: phone
				});
			},
			// 添加服务
			addService(tabIndex, productId, orderId) {
				const content = '是否确认发起' + (tabIndex === 0 ? '上游' : '下游') + '产品/订单服务？';
				this.showModal('使用服务', content, () => this.doAddService(tabIndex, productId, orderId));
			},

			// 执行添加服务
			doAddService(tabIndex, productId, orderId) {
			    const api = tabIndex === 0 ?
			        '/upper/upperMarketOrder/agriculture/addProductServe' :
			        '/down/downServiceOrder/agriculture/addDemandServe';
			
			    const requestData = tabIndex === 0 ? {
			        upperMarketProductId: productId // 这里是商品ID
			    } : {
			        downMarketDemandId: orderId // 这里是订单ID
			    };
			
			    const options = {
			        header: {
			            'Content-Type': 'application/x-www-form-urlencoded'
			        }
			    };
			
			    $H.post(api, requestData, options).then(res => {
			        uni.showToast({
			            title: res.message,
			            icon: 'success'
			        });
			    }).catch(error => {
			        console.error('网络错误，请稍后再试', error);
			        uni.showToast({
			            title: '网络错误，请稍后再试',
			            icon: 'none'
			        });
			    });
			},


			// 打开详情页
			openDetails(id, tabIndex) {
				const url = `/pages/tabbar/market/${tabIndex === 0 ? 'upstreamDetails' : 'downstreamDetails'}?id=${id}`;
				uni.navigateTo({
					url
				});
			},
			// 显示模态框
			showModal(title, content, callback) {
				uni.showModal({
					title: title,
					content: content,
					success: (res) => {
						if (res.confirm) {
							callback();
						}
					}
				});
			},
			// 切换标签页
			changeTab(index) {
				if (this.tabIndex === index) return;
				this.tabIndex = index;
				// 清空数据列表
				this.tabData = [];
				// 重置页码为 1
				this.form.pageNo = 1;
				// 设置标记为有更多数据
				this.hasMore = true;
				// 重新请求数据
				this.fetchData();
			},


			// 加载更多
			loadMore() {

				if (this.form.pageNo * this.form.pageSize >= this.form.total) {
					this.hasMore = false;
					return;
				}
				this.form.pageNo++;
				// 请求数据
				this.fetchData();
			},
			// 下拉刷新
			refresh() {
				// 重置页码为 1
				this.form.pageNo = 1;
				// 清空数据列表
				this.tabData = [];
				// 设置标记为有更多数据
				this.hasMore = true;
				// 重新请求数据
				this.fetchData();
				// 结束下拉刷新动画
				uni.$emit('stopPullDownRefresh');
			},
		},
	};
</script>

<style lang="scss" scoped>
	.tab-scroll {
		width: 100vw;
	}

	.tab-item {
		width: 50%;
		display: inline-block;
		text-align: center;
		padding: 0 10px;
		line-height: 40px;
	}
</style>